<template>

  <div class="pc-layout-view">
    <div class="pc-layout-view-header">
      <div class="header-left">
        <div class="navTitle">{{ projectTitle }}</div>
      </div>
      
      <div class="header-right">
        <div class="desktop-search-input-pc">
          <el-input v-model="searchParam.name" class="search-input" :prefix-icon="Search" placeholder="搜索模板" @keyup.enter="getTempList"/>
          <el-button type="success" @click="addTemplate">新增</el-button>
        </div>

        <div class="header-right-btns">
          <el-avatar :size="32" src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" style="margin-right: 10px;"/>
          <span class="user-name">管理员</span>
        </div>
      </div>
    </div>

    <div class="pc-layout-view-content">
      <div class="content-left">
        <el-menu :default-active="menu.activeMenu" class="menu" background-color="#f3f5f7" text-color="#000"
          active-text-color="#000" :unique-opened="true" router>
          <el-sub-menu :index="sub.path" v-for="(sub, index) in menu.list" :key="index">
            <template #title>
              <el-icon><component :is="sub.icon" /></el-icon>
              <span>{{ sub.title }}</span>
            </template>
            <el-menu-item v-for="(item, index) in sub.children" :key="index" :index="item.path">{{ item.title
              }}</el-menu-item>
          </el-sub-menu>
        </el-menu>
      </div>
      <div class="content-right">
        <div class="m-header"><span>我的模板</span></div>

        <template v-if="tempTypeList.length === 0" >
          <div class="tmall-empty">
            <div class="tmall-empty-img"></div>
            <div class="tmall-tell-us">暂无模板，请点击上方新增按钮创建模板</div>
          </div>
        </template>
        <template v-else>
          <div class="st-list">
            <div class="st-item" v-for="item in tempTypeList" :key="item.id">
              <div class="st-top">
                <div class="st-box">
                  <img :src="item.thumbnail" alt="">
                </div>
              </div>
              <div class="st-bottom">
                <div class="st-title">
                  <el-icon class="title-icon" size="18" color="#409eff"><List /></el-icon>
                  <span class="title-name">{{ item.name }}</span>
                </div>
              </div>
              <div class="hover-btn-wrap">
                <el-tooltip
                  effect="light"
                  content="预览"
                  placement="bottom"
                >
                  <el-button circle type="primary" :icon="View" @click="view(item)"></el-button>
                </el-tooltip>
                <el-tooltip
                  effect="light"
                  content="编辑"
                  placement="bottom"
                >
                  <el-button circle type="primary" :icon="Edit" @click="tempUse(item)"></el-button>
                </el-tooltip>
                <el-tooltip
                  effect="light"
                  content="删除"
                  placement="bottom"
                >
                  <el-button circle type="danger" :icon="DeleteFilled" @click="deleteTemplate(item.id)" />
                </el-tooltip>
              </div>
            </div>
          </div>
        </template>  
      </div>
    </div>
  </div>

  <!-- 新建方案对话框 -->
  <el-dialog
    v-model="templateModel.dialogVisible"
    title="新建模板"
    width="520"
  >
    <el-form 
      :model="templateModel.form" 
      :rules="templateModel.rules" 
      ref="templateFormRef" 
      label-width="90px"
      :label-position="'top'"
    >
      <el-form-item label="模板名称" prop="name">
        <el-input v-model="templateModel.form.name" maxlength="20" show-word-limit placeholder="请输入唯一的模板名称" />
      </el-form-item>
      <el-form-item label="所属行业" prop="industry">
        <el-select v-model="templateModel.form.industry" placeholder="请选择行业">
          <el-option v-for="item in industryList" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="templateModel.cancel">取消</el-button>
        <el-button type="primary" :loading="templateModel.loading" @click="templateModel.confirm">创建</el-button>
      </div>
    </template>
  </el-dialog>

  <ViewTempModel ref="viewTempModelRef" @tempUse="viewTempUse"/>
</template>
<script setup lang="ts">
import { Menu, Setting, Edit, List, Search, DeleteFilled, View } from '@element-plus/icons-vue'
import { ref, reactive, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { templateApi } from '@/api/template';
import { ElMessage, ElMessageBox } from 'element-plus'
import ViewTempModel from './ViewModel.vue'
import { industryList } from '@/constant/template'

const projectTitle = import.meta.env.VITE_PROJECT_TITLE;
const route = useRoute();
const router = useRouter();

const menu = reactive({
  activeMenu: route.path,
  list: [
    {
      title: '常用工具',
      icon: Menu,
      path: 'docs',
      children: [
        { title: '模板库', path: '/template' },
        { title: '知识库', path: '/category' },
        { title: '文档库', path: '/category' },
        { title: '提示词库', path: '/category' }
      ]
    },
    {
      title: 'AI工具',
      icon: Setting,
      path: 'system',
      children: [
        { title: '用户管理', path: '/user' },
        { title: '角色管理', path: '/role' }
      ]
    }
  ]
});

const searchParam = ref({
  name: ''
});

const tempTypeList = ref<any>([])


const viewTempModelRef = ref()
const view = (item: any) => {
  viewTempModelRef.value.open(item)
}

// 跳转到模板编辑页面
const tempUse = (item: any) => {
  // router.push({
  //   path: '/templateEdit/'+item.id,
  // })
  openNewWindowEdit(item);
}

// 预览弹窗组件-点击使用模板
const viewTempUse = (item: any) => {
  openNewWindowEdit(item)
}

// 获取模板列表
const getTempList = async () => {
  try {
    const res = await templateApi.getTempList(searchParam.value);
    if (res) {
      tempTypeList.value = res;
    } else {
      console.error('获取模板列表失败');
    }
  } catch (error) {
    console.error('请求错误:', error);
  }
}

const templateFormRef = ref();
const templateModel = reactive({
  dialogVisible: false,
  form: {
    name: '',
    industry: '',
    content: ''
  },
  rules: {
    name: [
      { required: true, message: '请输入模板名称', trigger: 'blur' }
    ],
    industry: [
      { required: true, message: '请选择行业', trigger: 'change' }
    ]
  },
  loading: false,

  cancel: () => {
    templateModel.dialogVisible = false;
    templateModel.form.name = '';
    templateModel.form.industry = '';
  },
  confirm: () => {
    templateFormRef.value.validate(async (valid:boolean) => {
        if (valid) {
          templateModel.loading = true;

          templateApi.createTemp(templateModel.form).then(res => {
            ElMessage.success('新建模板成功');
            templateModel.dialogVisible = false;
            // router.push({ path: '/templateEdit/'+ res.id });

           openNewWindowEdit(res);
          }).catch(error => {
            templateModel.loading = false;
            ElMessage.error('新建模板失败');
          });
        }
    });
  }
});

// 新增模板
const addTemplate = () => {
  templateModel.dialogVisible = true;
}

// 以新窗口的方式打开编辑模板页面
const openNewWindowEdit = (item: any) => {
  const { href } = router.resolve({
    path: '/templateEdit/' + item.id
  })
  window.open(href, '_blank')
}


// 删除模板
const deleteTemplate = async (id: string) => {
  ElMessageBox.confirm(
    '确认删除模板吗？',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    }
  ).then(async () => {
    try {
      await templateApi.removeTemp(id);
      ElMessage.success('删除模板成功');
      getTempList(); // 刷新列表
    } catch (error) {
      ElMessage.error('删除模板失败');
    }
  })
}

onMounted(() => {
  menu.activeMenu = route.path;
  getTempList();
});
</script>

<style lang="less" scoped>
.pc-layout-view {
  display: flex;
  flex: auto;
  flex-direction: column;
  min-height: 100vh;
  min-width: 630px;
  position: relative;
  height: 100%;
  background: #f3f5f7;
}

.pc-layout-view-header {
  display: flex;
  padding: 0 20px;
  height: 60px;
  flex: 0 0 auto;
  align-items: center;
  justify-content: space-between;

  .header-left{
    width: calc(244px - 20px);

    .navTitle {
      display: flex;
      align-items: center;
      min-width: 210px;
      flex-shrink: 0;
      font-size: 16px;
      font-weight: 500;
      height: 60px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      width: 200px;
    }
  }

  .header-right {
    flex: 1;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 16px;

    .desktop-search-input-pc{
      display: flex;
      flex: 1 1;
      margin-right: auto;
      max-width: 720px;
      min-width: 220px;

      .search-input{
        height: 40px;
      }

      :deep(.el-button) {
        height: 38px;
        line-height: 38px;
        margin-left: 15px;
      }
    }

    .header-right-btns{
      display: flex;
      align-items: center;
      .user-name {
        vertical-align: 10px;
      }
    }

    .home-btn {
      display: inline-block;
      width: 26px;
      height: 26px;
      background: url('@/assets/img/icon-home.png') no-repeat center / contain;
      cursor: pointer;
      transition: background-color 0.3s;

      &:hover {
        opacity: 0.8;
      }
    }
  }

}

.pc-layout-view-content {
  flex: 1;
  min-height: 0;
  position: relative;
  display: flex;
  height: 100%;
  overflow: hidden;

  .content-left {
    width: 244px;
    overflow-y: auto;
    border-right: 1px solid #e8e8e8;
  }

  .content-right {
    flex: 1;
    border-bottom: none;
    border-top-left-radius: 8px;
    border-top-right-radius: 8px;
    background-color: #fff;
    position: relative;
    height: 100%;
    margin: 0 12px 0 0;
    width: 100%;
    overflow: hidden;
  }
}

.el-menu{
  border-right: 0;
  :deep(.el-menu-item) {
    height: 36px;
    line-height: 36px;

    &.is-active {
      background-color: #fff;
      color: #409eff;
    }
  }
  :deep(.el-sub-menu) {
    .el-sub-menu__title {
      height: 36px;
      line-height: 36px;
    }
  }
}

@media screen and (min-width: 1300px) {
  .st-list {
    grid-template-columns: repeat(4, 1fr)!important;
  }
}
@media screen and (min-width: 1500px) {
  .st-list {
    grid-template-columns: repeat(5, 1fr)!important;
  }
}
@media screen and (min-width: 1600px) {
  .st-list {
    grid-template-columns: repeat(6, 1fr)!important;
  }
}



.st-list {
  grid-gap: 16px;
  align-items: start;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  justify-content: space-between;
  padding: 20px ;

  .st-item {
    position: relative;
    background: #fff;
    border: 1px solid rgba(0, 0, 0, .08);
    border-radius: 2px;
    box-shadow: 0px 1px 2px 0px rgba(0, 0, 0, .08);
    box-sizing: border-box;
    cursor: pointer;
    height: auto;
    opacity: 1;
    overflow: hidden;
    position: relative;
    width: 100%;
  }

  .st-top {
    padding: 12px 12px 0;

    .st-box {
      position: relative;
      border: 1px solid rgba(0, 0, 0, .04);
      border-radius: 4px;
      box-sizing: content-box;
      overflow: hidden;
      width: 100%;
      padding-bottom: 56.25%;

      img{
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
      }
    }
  }

  .st-bottom {
    display: flex;
    flex-direction: column;
    padding: 8px 10px;
    background: #fff;

    .st-title{
      display: flex;
      align-items: center;
      height: 20px;
      .title-icon{
        height: 20px;
        margin-right: 4px;
        width: 20px;
      }
      .title-name{
        color: rgba(0,0,0,.88);
        font-size: 14px;
        line-height: 20px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }

  .st-item:hover {
    .hover-btn-wrap {
      opacity: 1;
      visibility: visible;
    }
  }

  .hover-btn-wrap {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
    padding: 0 24px;
    position: absolute;
    left: 0;
    bottom: 0;
    background: rgba(0, 0, 0, .64);
    transition: all .1s;
    cursor: auto;
    z-index: 1;
    opacity: 0;
    visibility: hidden;

    .el-button {
      font-size: 16px;
    }
  }
}

.tmall-empty{
  align-items: center;
  display: flex;
  flex-direction: column;

  .tmall-empty-img{
    background-image: url(@/assets/img/empty.png);
    background-position: 50%;
    background-repeat: no-repeat;
    background-size: cover;
    height: 220px;
    margin-bottom: 4px;
    width: 220px;
  }
  .tmall-tell-us {
    margin: 40px 0;
    text-align: center;
    font-size: 16px;
    color: rgba(0,0,0,.4);
  }
}

.m-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 24px;
  border-bottom: 1px solid rgba(0, 0, 0,.04);
  border-bottom: 1px solid var(--border-weak, rgba(0, 0, 0,.04));
  font-size: 16px;
}
</style>